package org.timeticker.gui;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.io.Serializable;

/**
 * ComboBox renderer to display oject property using reflection
 *
 * @author Ivan Latysh
 * @version 0.1
 * @since 11-Aug-2007 : 6:35:54 PM
 */
public class ObjectComboBoxRenderer extends JLabel implements ListCellRenderer, Serializable {

  /** Bean peroperty to display */
  protected String property;

  public ObjectComboBoxRenderer(String property) {
    super();
    this.property = property;
    setOpaque(true);
    setBorder(new EmptyBorder(1, 1, 1, 1));
  }

  public Dimension getPreferredSize() {
    Dimension size;
    if ((this.getText() == null) || (this.getText().equals(""))) {
      setText(" ");
      size = super.getPreferredSize();
      setText("");
    } else {
      size = super.getPreferredSize();
    }
    return size;
  }

  public Component getListCellRendererComponent(
          JList list,
          Object value,
          int index,
          boolean isSelected,
          boolean cellHasFocus) {

    if (isSelected) {
      setBackground(list.getSelectionBackground());
      setForeground(list.getSelectionForeground());
    } else {
      setBackground(list.getBackground());
      setForeground(list.getForeground());
    }

    setFont(list.getFont());

    if (null!=value && null!=property) {
      setText(String.valueOf(BeanHelper.getPropertyValue(value, property)));
    } else if (value instanceof Icon) {
      setIcon((Icon) value);
    } else {
      setText((value == null) ? "" : value.toString());
    }

    return this;
  }

}
